from random import randint
from django.shortcuts import render
from itsdangerous import TimedJSONWebSignatureSerializer
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cookie_redis_cart
from goods.models import SKU
from mall import settings
from .models import User
from rest_framework.generics import GenericAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView,ListAPIView
from rest_framework import mixins
from . import serializers
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms_code
class CheckUsernameView(APIView):
    def get(self,request,username):

        #1,根据用户名查询,用户数量
        count = User.objects.filter(username=username).count()

        #2,返回响应
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)

class CheckMobileView(APIView):
    def get(self,request,mobile):

        #1,根据手机号查询,用户数量
        count = User.objects.filter(mobile=mobile).count()

        #2,返回响应
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)

class RegisterUserView(CreateAPIView):
    serializer_class = serializers.RegisterUserSerializer

    # def post(self,request):
        #一, 只继承自了GenericAPIView
        # #1,获取参数
        # dict_data = request.data
        #
        # #2,创建序列化器,校验
        # serializer =  self.get_serializer(data=dict_data)
        # serializer.is_valid(raise_exception=True)
        #
        # #3,数据入库
        # serializer.save()
        #
        # #4,返回响应
        # return Response(serializer.data,status=status.HTTP_201_CREATED)

        #二,使用了mixin + GenericAPIView
        # return self.create(request)

class UserInfoView(RetrieveAPIView):
    serializer_class = serializers.UserInfoSerializer

    permission_classes = [IsAuthenticated] #认证的用户

    def get_object(self):
        return self.request.user

    # def get(self,request):
    #     #一, 单纯使用二级视图实现
    #     # #1,获取用户对象(或者request.user)
    #     # user =  self.get_object()
    #     #
    #     # #2,创建序列化对象
    #     # serializer = self.get_serializer(instance=user)
    #     #
    #     # #3,返回数据
    #     # return Response(serializer.data)
    #
    #     #二,二级视图配合mixin
    #     return self.retrieve(request)

class EmailSendView(UpdateAPIView):
    serializer_class = serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        return self.request.user

    # def put(self,request):
    #     #一, 单纯使用二级视图实现
        # #1,获取数据
        # dict_data = request.data
        # user = self.get_object()
        #
        # #2,获取序列化器
        # serializer = self.get_serializer(instance=user,data=dict_data)
        #
        # #3,校验,入库
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # #4,返回
        # return Response(serializer.data)
    #     #二,二级视图配合mixin
        # return self.update(request)

class EmailActiveView(APIView):
    def get(self,request):
        #1,获取参数token
        token = request.query_params.get("token")

        #2,为空校验
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #3,解密token
        user = User.decode_token(token)
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #4,数据入库(修改email_active属性)
        user.email_active = True
        user.save()

        #5,返回响应
        return Response(status=status.HTTP_200_OK)

class AddressView(mixins.CreateModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  GenericViewSet):
    serializer_class = serializers.AddressSerializer

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self,request):

        # 1,获取用户地址信息
        queryset = self.get_queryset()

        #2,获取序列化器
        serializer = self.get_serializer(instance=queryset,many=True)

        #3,返回
        return Response({
            "addresses":serializer.data,
            "limit":20,
            "default_address_id":request.user.default_address_id
        })

    #1,重写地址创建方法,判断用户的地址是否已经达到20个了
    def create(self, request, *args, **kwargs):
        # #1,获取参数
        # dict_data = request.data
        #
        # #2,获取序列化器
        # serializer = self.get_serializer(data=dict_data)
        #
        # #3,校验入库
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # #4,返回
        # return Response(serializer.data)

        #1,获取用户地址数量
        count =  request.user.addresses.filter(is_deleted=False).count()

        #2,判断地址的数量
        if count >= 20:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #3,调用父类方法即可
        return super(AddressView, self).create(request,*args,**kwargs)

    #2,更改用户默认地址
    @action(methods=['put'],detail=True) #格式: addresses/pk/status
    def status(self,request,pk):
        request.user.default_address_id = pk
        request.user.save()
        return Response(status=status.HTTP_200_OK)

    #3,修改地址的标题
    @action(methods=["put"],detail=True)
    def title(self,request,pk):
        #1,获取参数
        dict_data = request.data
        address = self.get_object()

        #2,创建序列化器
        serializer = serializers.AddressTitleSerializer(instance=address,data=dict_data)

        #3,校验数据,入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        #4,返回
        return Response(serializer.data)

    #4,重写destory方法,为了逻辑删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)


class TestView(APIView):
    def get(self,request,name,age):
        print(self.kwargs) #获取的就是地址中,写带的资源参数
        return Response("%s,%s"%(name,age))

class UserBrowerHistoryView(CreateAPIView):
    serializer_class =serializers.UserBrowerHistorySerializer

    # def post(self,request):
    #
    #     #1,获取参数
    #     dict_data = request.data
    #
    #     #2,获取序列化器,校验
    #     serializer = self.get_serializer(data=dict_data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     #3,入库(保存到redis中)
    #     serializer.save()
    #
    #     #4,返回
    #     return Response(serializer.data)

    def get(self,request):
        #1,获取redis中的数据
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s"%request.user.id,0,4)

        #2,拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "default_image_url":sku.default_image_url,
                "name":sku.name,
                "price":sku.price,
                "comments":sku.comments,
                "id":sku.id
            }
            sku_list.append(sku_dict)

        #3,返回
        return Response(sku_list)

#重写登陆类视图
class UserObtainJSONWebToken(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):

        #1,调用父类方法
        response = super().post(request, *args, **kwargs)

        #2,获取序列化器
        serializer = self.get_serializer(data=request.data)

        #3,判断是否认证成功
        if serializer.is_valid():

            #3.1获取user对象
            user = serializer.validated_data.get("user")

            #3.2合并购物车
            response = merge_cookie_redis_cart(request,user,response)

        return response


# 展示用户订单
class ListUserOrderView(ListAPIView):
    serializer_class = serializers.ListUserOrderSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.orderinfo_set.all()

#修改密码
class UpdatePasswordView(APIView):
    def put(self, request, pk):
        """修改密码"""
        user = request.user
        if user and user.is_authenticated:
            # 获取参数
            old_pwd = request.data.get('old_password')
            pwd = request.data.get('password')
            pwd2 = request.data.get('password2')
            # 检验参数
            if not user.check_password(old_pwd):
                return Response({'message': '原密码不正确'}, status=status.HTTP_400_BAD_REQUEST)
            if pwd != pwd2:
                return Response({'message': '两次密码不一致'}, status=status.HTTP_400_BAD_REQUEST)
            # 保存新密码
            try:
                user.set_password(pwd)
                user.save()
            except:
                return Response({'message': '数据库错误'}, status=status.HTTP_400_BAD_REQUEST)
            return Response({'message': 'OK'})
        return Response(status=status.HTTP_403_FORBIDDEN)



class CheckUserView(APIView):
    def get(self, request, mobile):
        """检查用户是否存在（用户名或者手机号）"""
        # 1 获取参数
        dict_data = request.query_params.dict()
        dict_data['mobile'] = mobile

        # 2 验证参数
        s = serializers.ChecKUserViewSerializer(data=dict_data)
        s.is_valid(raise_exception=True)

        # 获取验证后的参数
        dict_data = s.validated_data
        # print("dict_data:", dict_data)

        # 判断用户是否存在
        user = dict_data.get('user')
        if not user:
            return Response(status=status.HTTP_404_NOT_FOUND)

        # 通过itsdangerous模块封装的TimedJSONWebSignatureSerializer类获取带有有效期的token
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 300)
        # serializer.dumps(数据), 返回bytes类型
        token = serializer.dumps({'mobile': user.mobile}).decode()
        # print(token)

        return Response({'mobile': user.mobile, 'access_token': token})
class SendSmsCodeView(APIView):
    def get(self, request):
        """发送短信验证码"""
        # 1 获取参数
        access_token = request.query_params.get('access_token')

        # 2 检验参数
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 300)
        try:
            dict_data = serializer.loads(access_token)
            # print(dict_data,"asdasd")
        except Exception as e:
            return Response({'message': 'access_token已过期'},status=status.HTTP_400_BAD_REQUEST)

        # 判断请求间隔是否在60s内
        mobile = dict_data.get('mobile')
        redis_conn = get_redis_connection('code')
        flag = redis_conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'message': '请求过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 3 生成短信验证码，将短信验证码保存在redis缓存中
        sms_code = '%06d' % randint(0, 999999)
        print('sms_code:%s' % sms_code)
        redis_conn.setex('sms_code_%s' % mobile, 300, sms_code)
        redis_conn.setex('sms_code_flag_%s' % mobile, 60, 2)

        # 4 发送短信
        # send_sms_code.delay(mobile, sms_code)

        # 5、返回结果
        return Response({'message': 'ok'})
class CheckSmsView(APIView):
    def get(self, request, mobile):
        # 获取参数
        dict_data = request.query_params.dict()
        dict_data['mobile'] = mobile

        # 验证参数
        s = serializers.CheckSmsSerializer(data=dict_data)
        s.is_valid(raise_exception=True)

        # 获取用户
        user = s.validated_data.get('user')
        if not user:
            return Response(status=status.HTTP_404_NOT_FOUND)

        # 通过itsdangerous模块封装的TimedJSONWebSignatureSerializer类获取带有有效期的token
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 300)
        # serializer.dumps(数据), 返回bytes类型
        token = serializer.dumps({'user_id': user.id}).decode()

        # 返回数据
        return Response({'user_id': user.id, 'access_token': token})

#找回密码
class ChangePasswordView(APIView):
    def post(self,request,pk):
        """找回密码"""
        #获取参数
        dict_data=request.data
        #获取参数里面的access_token
        access_token=dict_data.get('access_token')
        pwd=dict_data.get('password')
        pwd2=dict_data.get('password2')
        #校验参数
        try:
            serializer=TimedJSONWebSignatureSerializer(settings.SECRET_KEY,300)
            #serializer.dumps(数据)获得bytes类型
            token=serializer.loads(access_token)
        except:
            return Response({'message':'access_token过期'}, status=status.HTTP_400_BAD_REQUEST)
        if pwd !=pwd2:
            return Response({'message':'两次密码不一致'},status=status.HTTP_400_BAD_REQUEST)
        try:
            user =User.objects.get(pk = pk)
        except:
            return Response({'message':'用户不存在'},status=status.HTTP_400_BAD_REQUEST)
                #检验用户id是否被篡改过
        if user.id !=token.get('user_id'):
            return Response({'message':'ok'})
        #设置密码
        try:
            user.set_password(pwd)
            user.save()
        except:
            return Response({'message':'数据库错误'},status=status.HTTP_400_BAD_REQUEST)
        return Response({"message":"ok"})

